const app = getApp();
Page({
  data: {
    flash: 'off',
    src: '',
    preview: false,
    lamptitle: '已关闭',
  },
  
  onLoad() {
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#000000',
    });
    this.ctx = wx.createCameraContext();
  },

  takePhoto() {
    let that = this;
    that.ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        that.setData({
          src: res.tempImagePath,
          preview: true,
        });
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },

  // ORC 接口调用
  createCard() {
    let that = this;
    wx.showLoading({ title: '生成中...', mask: true });

    let url = 'utility/file/upload';
    if (!url.includes('http://') && !url.includes('https://')) {
      url = app.util.url(url, { type: 'image', thumb: '0' });
    }
    that.data.src ? wx.uploadFile({
      url,
      filePath: that.data.src,
      name: 'file',
      success: function(res) {
        let data = JSON.parse(res.data);
        if (res.statusCode === 200 && !data.error && data.url) {
          app.util.request({
            url: 'card/api/upload_card',
            data: { card_url: data.url },
            cachetime: 0,
            success: res => {
              if (res.data.errno === 0) {
              app.util.navigateTo('/common/component/universal-card/card-preview', {}, true);
              } else {
                wx.hideLoading();
                that.showTostInfo(res.data.message || '图片解析异常，请调整后重新拍摄！');
                that.setData({ preview: false });
              }
            },
            fail: function(res) {
              wx.hideLoading();
              that.showTostInfo(res.data.message || '图片解析异常，请调整后重新拍摄！');
              that.setData({ preview: false });
            },
          });
        }
        if (!data.url) {
          that.setData({ src: '' });
          that.showTostInfo('接口图片路径出错');
        }
      },
      fail: function (res) {
        wx.hideLoading();
        that.showTostInfo('上传失败 请重试');
      },
    }) : wx.showToast({
      title: '拍摄的图片有误！',
          icon: 'none',
          mask: true,
        });
      },

  showTostInfo(msg) {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 1500,
      mask: true,
    });
  },

  cancel() {
    !this.data.preview ? wx.navigateBack({ delta: 1 }) : this.setData({ src: '', preview: false });
  },

  openLamp() {
    let that = this;
    let thisflash = that.data.flash;
    that.setData({
      flash: thisflash === 'on' ? 'off' : 'on',
      lamptitle: thisflash === 'on' ? '已关闭' : '已开启',
    });
  },
});
